package com.jeegot.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeegot.core.utils.StrUtils;
import com.jeegot.mall.entity.PostageTemplate;
import com.jeegot.mall.entity.PostageTemplateSet;
import com.jeegot.mall.entity.Product;
import com.jeegot.mall.mapper.PostageTemplateMapper;
import com.jeegot.mall.service.IOrderService;
import com.jeegot.mall.service.IPostageTemplateService;
import com.jeegot.mall.service.IPostageTemplateSetService;
import com.jeegot.mall.service.IProductService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * <p>
 * 运费模板表 服务实现类
 * </p>
 *
 * @author wjun_java@163.com
 * @since 2021-06-10
 */
@Service
public class PostageTemplateServiceImpl extends ServiceImpl<PostageTemplateMapper, PostageTemplate> implements IPostageTemplateService {

	@Autowired
	private IPostageTemplateSetService postageTemplateSetService;

	@Autowired
	private IProductService productService;

	@Override
	@Transactional
	public void savePostageTemplate(PostageTemplate postageTemplate) throws Exception {
		PostageTemplate template = getById(postageTemplate.getId());

		if(template == null) {
			template = new PostageTemplate();
		}

		template.setTemplateName(postageTemplate.getTemplateName());
		template.setShippingTime(postageTemplate.getShippingTime());
		template.setTemplateType(postageTemplate.getTemplateType());
		template.setValuationType(postageTemplate.getValuationType());
		saveOrUpdate(template);

		if(1== postageTemplate.getTemplateType()) {
			//包邮
			return;
		}

		String [] template_set_id = postageTemplate.getTemplateSetId();
		String [] start_standards = postageTemplate.getStartStandards();
		String [] start_fees = postageTemplate.getStartFees();
		String [] add_standards = postageTemplate.getAddStandards();
		String [] add_fees = postageTemplate.getAddFees();
		String [] selectedareas = postageTemplate.getSelectedareas();

		if("".equals(start_standards[0]) || "".equals(start_fees[0]) || "".equals(add_standards[0]) || "".equals(add_fees[0])) {
			throw new Exception("请填写默认运费设置");
		}

		//原数据1,2,3,4,5
		//提交的数据2,3,5
		//删除1,4
		List<PostageTemplateSet> postageTemplateSetList = postageTemplateSetService.getTemplateSetList(postageTemplate.getId());
		if(postageTemplateSetList != null && postageTemplateSetList.size()>0) {
			Map<String, Integer> tempMap = new HashMap<>();
			for(PostageTemplateSet postageTemplateSet : postageTemplateSetList) {
				tempMap.put(String.valueOf(postageTemplateSet.getId()), 1);
			}
			for(int i=0; i<template_set_id.length; i++) {
				String key = template_set_id[i];
				if(StringUtils.isNotBlank(key)) {
					if(tempMap.get(key) != null) {
						tempMap.put(key, tempMap.get(key) + 1);
					}else {
						tempMap.put(key, 1);
					}
				}
			}

			tempMap.keySet().forEach(item -> {
				if(tempMap.get(item) == 1) {
					postageTemplateSetService.removeById(item);
				}
			});

		}

		for(int i=0; i<start_standards.length;i++) {
			PostageTemplateSet postageTemplateSet = postageTemplateSetService.getById(template_set_id[i]);
			if(postageTemplateSet == null){
				postageTemplateSet = new PostageTemplateSet();
				postageTemplateSet.setTemplateId(postageTemplate.getId());
			}

			postageTemplateSet.setStartStandards(Integer.valueOf(start_standards[i]));
			postageTemplateSet.setStartFees(new BigDecimal(start_fees[i]));
			postageTemplateSet.setAddStandards(Integer.valueOf(add_standards[i]));
			postageTemplateSet.setAddFees(new BigDecimal(add_fees[i]));
			postageTemplateSet.setAreaContent(selectedareas[i]);
			postageTemplateSetService.saveOrUpdate(postageTemplateSet);
		}
	}

	@Override
	public List<PostageTemplate> getUserPostageTemplate(Long userId) {
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("user_id", userId);
		return list(queryWrapper);
	}

	@Override
	public BigDecimal getPostageAmount(IOrderService.ProductParam productParam, String address) {
		AtomicReference<BigDecimal> postageAmount = new AtomicReference<>(BigDecimal.ZERO);
		if(StrUtils.isBlank(address)) {
			return postageAmount.get();
		}
		String[] addressItem = address.split(" ");
		if(addressItem.length <=0) {
			return postageAmount.get();
		}
		Product product = productService.getById(productParam.getId());
		if(product.getPostageTemplateId() != null){
			PostageTemplate postageTemplate = getById(product.getPostageTemplateId());
			if(postageTemplate != null && postageTemplate.getTemplateType() == PostageTemplate.TEMPLATE_TYPE_CUSTOM) {

				QueryWrapper queryWrapper = new QueryWrapper();
				queryWrapper.eq("template_id", postageTemplate.getId());
				queryWrapper.orderByDesc("created");
				List<PostageTemplateSet> freightTemplateSetList = postageTemplateSetService.list(queryWrapper);

				AtomicBoolean isMatched = new AtomicBoolean(false);
				long productCount = productParam.getNum();//商品数量

				freightTemplateSetList.stream().filter(item->!"default".equals(item.getAreaContent())).forEach(item ->{

					for (String s : addressItem) {
						if(item.getAreaContent().contains(s)) {
							isMatched.set(true);
							break;
						}

					}

					if(isMatched.get()){

						if(productCount <= item.getStartStandards()){
							//按标准价格
							postageAmount.set(postageAmount.get().add(item.getStartFees()));
						}else{
							//超过标准数量
							long overCount = productCount - item.getStartStandards();
							postageAmount.set(postageAmount.get().add(item.getStartFees()).add(new BigDecimal(overCount).multiply(item.getAddFees())));
						}
					}
				});

				if(isMatched.get() == false){
					//没有匹配上地址的情况，使用默认的
					List<PostageTemplateSet> defaultFreightTemplateSets = freightTemplateSetList.stream().filter(item->"default".equals(item.getAreaContent())).collect(Collectors.toList());
					if(defaultFreightTemplateSets != null && defaultFreightTemplateSets.size()>0){
						PostageTemplateSet item = defaultFreightTemplateSets.get(0);
						if(item != null){
							if(productCount <= item.getStartStandards()){
								//按标准价格
								postageAmount.set(postageAmount.get().add(item.getStartFees()));
							}else{
								//超过标准数量
								long overCount = productCount - item.getStartStandards();
								postageAmount.set(postageAmount.get().add(item.getStartFees()).add(new BigDecimal(overCount).multiply(item.getAddFees())));
							}
						}

					}
				}
			}
		}
		return postageAmount.get().setScale(2, BigDecimal.ROUND_HALF_UP);
	}

	@Override
	public BigDecimal getPostageAmount(GetPostageAmountParam getPostageAmountParam) {

		if(StrUtils.isBlank(getPostageAmountParam.getAddress())) {
			return BigDecimal.ZERO;
		}

		BigDecimal postageFee = BigDecimal.ZERO;
		for (IOrderService.ProductParam productParam : getPostageAmountParam.getProductParamList()) {
			postageFee = postageFee.add(getPostageAmount(productParam, getPostageAmountParam.getAddress()));
		}

		return postageFee;
	}

}
